//
//  YKCache.m
//  YK_BaseTools
//
//  Created by edward on 2020/10/11.
//  Copyright © 2020 Edward. All rights reserved.
//

#import "YKCache.h"
#import <YYCache/YYCache.h>

@interface YKCache ()


/// 缓存用户信息的缓存池
@property (nonatomic,strong) YYCache *cache;
@end

@implementation YKCache

static YKCache *_instance;

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });

    return _instance;
}

+ (instancetype)sharedInstance
{
    if (_instance == nil) {
        _instance = [[YKCache alloc] init];
    }

    return _instance;
}

+ (void)toSetValue:(id<NSCoding>)value forKey:(nonnull NSString *)key
{
    [[YKCache sharedInstance].cache.diskCache setObject:value forKey:key];
}

+ (id<NSCoding>)objectForKey:(NSString *)key
{
    return [[YKCache sharedInstance].cache.diskCache objectForKey:key];
}

+ (void)removeObjectForKey:(NSString *)key
{
    [[YKCache sharedInstance].cache.diskCache removeObjectForKey:key];
}

- (YYCache *)cache
{
    if (!_cache) {
        NSString *cacheName = [[NSUserDefaults standardUserDefaults] valueForKey:@"YKBaseCache_cacheName"];
        if (!cacheName) {
            cacheName = [[NSUUID UUID] UUIDString];
            [[NSUserDefaults standardUserDefaults] setValue:cacheName forKey:@"YKBaseCache_cacheName"];
        }
        _cache = [YYCache cacheWithName:cacheName];
    }
    return _cache;
}

@end
